<template>
  <!-- 退费详情 -->
  <section>
    <div style="border-bottom:1px solid #eee;padding-bottom:10px;">
      <el-page-header @back="goBack" content="账单详情"></el-page-header>
    </div>
    <br />
    <div class="visit_detail_box">
      <div class="userinfo p-sm">
        <p v-if="detail">
          <img v-if="detail.head!=''" :src="detail.head | imageUrl" class="patient_img" alt />
          <img v-else src="/img/unknown-avatar.4f0c79ac.png" class="patient_img" alt />
        </p>
        <p v-if="detail">
          <span style="font-size: 20px; margin-right: 20px; vertical-align: middle;">{{detail.name}}</span>
          <i class="glyphicon glyphicon-earphone" style="vertical-align: middle; font-size: 18px;"></i>
        </p>
        <!-- <div v-if="detail" class="user-field">
          <span>挂账：</span>
          {{detail.chargeToTheRoom? detail.chargeToTheRoom : 0 | changeMoneyToTwo}}
        </div>-->
        <div v-if="detail" class="user-field">
          <span>性别：</span>
          {{detail.sex | toSex}}
        </div>
        <div v-if="detail" class="user-field">
          <span>年龄：</span>
          <!-- <label v-if="detail.age>7">{{detail.age}}岁</label>
          <label v-if="detail.age<7">{{detail.age}}岁{{detail.sdfMonth}}月{{detail.sdfDay}}天</label>-->
          <label v-if="detail.age>17">{{detail.age}}</label>
          <label v-else>{{detail.birthday|toTimeContrast}}</label>
        </div>
        <div v-if="detail" class="user-field">
          <span>门诊号：</span>
          <span style="color: red;">{{detail.archivesCode}}</span>
        </div>
      </div>
      <div class="user-content p-sm">
        <el-row style="margin:10px 0px;display:inline-block;width:100%;">
          <el-col :span="6">
            <label style="font-size:16px;">收费项目</label>
          </el-col>
          <el-col style="height:10px;" :span="6"></el-col>
          <el-col style="height:10px;" :span="6"></el-col>
        </el-row>
        <el-row style="margin:10px 0px;">
          <el-col :span="6">收费科室：{{curInfo.deptName}}</el-col>
          <el-col :span="6">收费医生：{{curInfo.doctorName}}</el-col>
          <el-col :span="6">收费人员：{{curInfo.operateName}}</el-col>
          <el-col :span="6">收费时间：{{curInfo.cureTime}}</el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <table class="table-box">
              <thead>
                <tr>
                  <th v-if="isGo">
                    <el-checkbox
                      :indeterminate="isIndeterminate"
                      v-model="checkAll"
                      :disabled="isRemaber"
                      @change="handleCheckAllChange"
                    ></el-checkbox>
                  </th>
                  <th>收费名称</th>
                  <th>单价</th>
                  <th>数量</th>
                  <th>单位</th>
                  <th>折扣</th>
                  <th>是否套餐抵扣</th>
                  <th>核销数量</th>
                  <th>实收金额</th>
                  <th>退费金额</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item,index) in itemList" :key="index">
                  <template v-if="item.source !='13'">
                    <td v-if="isGo" class="return-item_td">
                      <el-checkbox-group
                        v-model="checkedAdmin"
                        @change="handleCheckedCitiesChange($event,item.sourceId,item.totalAmount,item.actualAmount)"
                      >
                        <el-checkbox :label="item.sourceId" :disabled="(item.packageWriteOff || item.memberGive) ?true:false" :key="item.sourceId"></el-checkbox>
                      </el-checkbox-group>
                    </td>
                    <td>{{item.sourceName}}</td>
                    <td>￥{{item.unitPrice!=undefined?item.unitPrice:item.oneMoney }}</td>
                    <td>{{item.number?item.number:item.frequency}}</td>
                    <td>{{item.unitName}}</td>
                    <td>
                     {{item.discount}}折
                    </td>
                    <td style="text-align:center;">{{item.packageWriteOff==0?"否":"是"}}</td>
                    <td style="text-align:center;">{{item.packageWriteOffNumber}}</td>
                    <td>￥{{item.actualAmount}}</td>
                    <td>
                      <el-input
                       v-if="item.packageWriteOff==0"
                       @blur="changeDis(item,2)"
                        v-model="item.refundAmount"
                      >
                        <template slot="prepend">￥</template>
                      </el-input>
                      <label v-else>￥{{item.refundAmount}}元</label>
                    </td>
                  </template>
                </tr>
              </tbody>
            </table>
          </el-col>
        </el-row>
        <el-row v-if="tsList.length>0" class="moeny_box" style="margin-top:10px;">
          <el-col class="other" style="height:20px;font-size:16px;margin:5px 0;" :span="24">特殊收费项目</el-col>
          <el-col :span="24">
            <table class="table-box">
              <thead>
                <tr>
                  <th>
                    <el-checkbox
                      v-model="checkComboAll"
                      @change="changeCombo"
                    ></el-checkbox>
                  </th>
                  <th>收费名称</th>
                  <th>原价</th>
                  <th>数量</th>
                  <th>套餐价</th>
                  <th>退款金额</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(it,index) in tsList" :key="index">
                  <td>
                    <el-checkbox-group
                      v-model="checkedCombo"
                      class="pay_check_box"
                      @change="tsChange($event,it.sourceId,it.actualAmount)"
                    >
                      <el-checkbox :label="it.sourceId" :key="it.sourceId"></el-checkbox>
                    </el-checkbox-group>
                  </td>
                  <td>{{it.sourceName}}</td>
                  <td>￥{{it.totalAmount}}</td>
                  <td>{{it.number}}</td>
                  <td>￥{{it.totalAmount}} </td>
                  <td>
                      <el-input
                       @blur="changeTcSf(it,it.refundAmount)"
                        v-model="it.refundAmount"
                      >
                        <template slot="prepend">￥</template>
                      </el-input>
                  </td>
                  <td>
                    <el-link @click="getDetail(it)">使用详情</el-link>
                  </td>
                </tr>
              </tbody>
            </table>
          </el-col>
        </el-row>
        <el-row class="money_box">
          <el-col class="other" :span="18"></el-col>
          <el-col class="money" :span="6">
            <label>费用合计：</label>
            <span>￥ {{totalMoney | changeMoneyToTwo}}</span>
          </el-col>
        </el-row>
        <el-row class="money_box">
          <el-col class="other" :span="18"></el-col>
          <el-col class="money" :span="6">
            <label>实收金额：</label>
            <span>￥{{total | changeMoneyToTwo}}</span>
          </el-col>
        </el-row>
        <el-row class="money_box">
          <el-col class="other" :span="18"></el-col>
          <el-col class="money" :span="6">
            <label>折扣金额：</label>
            <span>￥{{disAmount | changeMoneyToTwo}}</span>
          </el-col>
        </el-row>
        <el-row style="margin-top:20px;">
          <el-button
            style="float:right;"
            @click="onBeforeSubmit"
          >退费</el-button>
        </el-row>
      </div>
    </div>
    <dialogReturn v-if="showReturn" v-model="showReturn" :orderId="orderId" :tsItemList="tsItemList" :checkItemList="checkItemList"></dialogReturn>
    <dialogTcDetail v-if="showDetail" v-model="showDetail" :source="source" :sourceId="sourceId" ></dialogTcDetail>
  </section>
</template>
<script>
import dialogReturn from '../_com/dialogReturn';
import dialogTcDetail from '../_com/dialogTcDetail'
import calculate from '../_js/calculate'
export default {
  name: "chargeDetail",
  // returnPayArr
  data() {
    return {
      dialogRecord: false,
      detail: "",
      checkedAdmin: [],
      checkAll:false,
      isIndeterminate: false,
      isCombo: true,
      checkedCombo: [],
      checkComboAll: [],
      itemList: [],
      tsList: [], //特殊项目
      total: 0,
      totalMoney: 0.0, //总金额
      dwList: [],
      disAmount: 0.0,
      integralNum: 0,
      doctorId: 0,
      deptId: 0,
      deptName:'',
      doctorName:'',
      //套餐二级id
      userPackageItemId:'',
      showOrder: false,
      btnLoading: false,
      isGo: true,
      curInfo:{
        deptName:'',
        doctorName:'',
        operateName:'',
        cureTime:'',
        createTime:'',
        balance:0,
      },
      showReturn:false,
      checkItemList:[],
      tsItemList:[],
      orderId:'',
      showDetail:false,
      sourceId:'',
      source:'',
      isRemaber:false,
    };
  },
  created() {
  },
  mounted() {
    this.getBasic();
    this.findUsUserById();
    this.getItemDetail();
    this.isGo = this.$route.query.isOrder ? false : true;
  },
  methods: {
    getItemDetail() {
      let id = this.$route.query.id;
      this.orderId=id;
      this.$api.getOrderDetailByMedical({ orderId: id }).then((res) => {
        if (res.executed) {
          let { list , cureTime , deptName , doctorName , operateName , totalAmount , actualAmount ,payTime,source}=res.dataBody;
          this.curInfo={
            cureTime , deptName , doctorName , operateName ,payTime
          }
          list=list.map(it=>{
            return {...it,refundAmount:0}
          })
          let num=0;
          this.itemList=list.filter(it=>{
             if(it.packageWriteOff || it.memberGive){
                num++;
             }
             if(it.source!=13){
              //  this.checkedAdmin.push(it.sourceId);
              //  this.checkAll=true;
               return it;
             }
          })
          this.tsList=list.filter(it=>{
             if(it.source==13){
              //  this.checkComboAll=true;
              //  this.checkedCombo.push(it.sourceId);
               return it;
             }
          })
          if(num>0){
             this.isRemaber=true;
           }
          this.totalMoney=totalAmount;
          this.total=actualAmount;
          this.source=source;
          this.disAmount=Number(totalAmount - actualAmount).toFixed(2);
        }
      });
    },
    //获取患者详情
    findUsUserById() {
      let uid = this.$route.query.patientId;
      this.showLoading();
      this.$api
        .getThePatientLibraryById({ patientId: uid, hpId: this.adminUser.hpId })
        .then((res) => {
          if (res.executed) {
            this.detail = res.thePatientLibraryDetail;
            this.showLoading(false);
          } else {
            this.showLoading(false);
            this.$message.error(res.message);
          }
        });
    },
    getBasic() {
      let th = this;
      th.getCommonConfigByKey("药品剂量单位").then((res) => {
        th.dwList = res;
      });
    },
    /**
     * 获取折扣数/折后金额
     * @param {type}  1、获取折后价格  2、获取折扣数
     * @param {discount}  折数
     * @param {actualAmount} 优惠价
     * @param {totalAmount} 原价
     */
    changeDis(item,type) {
        const { discount,actualAmount,totalAmount } =item;
        let reg=/((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
       if(!reg.test(item.refundAmount)){
         item.refundAmount=0;
         this.$message.warning("请输入正确的退费金额");
          return false;
       }
        if(item.totalAmount<item.refundAmount){
          this.$message.warning("退费金额不能大于实收金额");
          item.refundAmount=item.totalAmount;
          return false;
        }
        let list=this.itemList.filter(it=>{
          if(!it.packageWriteOff && !it.memberGive ){
            return it;
          }
        })
        // item.actualAmount=Number(item.totalAmount-item.refundAmount).toFixed(2);
        // if(this.checkedAdmin.includes(item.sourceId)){
        //   let {oldTotalMoney , newTotalMoney , discountMoney} = calculate.calculateTotalByList(list);
        //   let tcObj= calculate.calculateTotalByList(this.tsList);
        //   this.total=Number(newTotalMoney+tcObj.newTotalMoney);
        //   this.totalMoney=Number(oldTotalMoney+tcObj.oldTotalMoney);
        //   this.disAmount=Number(discountMoney+tcObj.discountMoney);
        // }
    },
    changeTcSf(item,money){
      if(item.totalAmount<money){
          this.$message.warning("退费金额不能大于实收金额");
          item.refundAmount=item.totalAmount;
          return false;
        }
      let list=this.itemList.filter(it=>{
          if(!it.packageWriteOff && !it.memberGive ){
            return it;
          }
        })
        // item.actualAmount=Number(item.totalAmount-money).toFixed(2);
        // if(this.checkedCombo.includes(item.sourceId)){
        //   let {oldTotalMoney , newTotalMoney , discountMoney} = calculate.calculateTotalByList(list);
        //   let tcObj= calculate.calculateTotalByList(this.tsList);
        //   this.total=Number(newTotalMoney+tcObj.newTotalMoney);
        //   this.totalMoney=Number(oldTotalMoney+tcObj.oldTotalMoney);
        //   this.disAmount=Number(discountMoney+tcObj.discountMoney);
        // }
    },
    handleCheckedCitiesChange(value, id,oldMoney , money) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.itemList.length;
        this.isCombo = checkedCount > 0 && checkedCount < this.itemList.length;
        let bools = value.includes(id);
        // if(bools){
        //   this.total+=Number(money);
        //   this.totalMoney+=Number(money);
        //   this.disAmount+=Number(oldMoney-money);
        // }else{
        //   this.total-=money;
        //   this.totalMoney-=money;
        //   this.disAmount-=(oldMoney-money);
        // }
    },
    changeCombo(val) {
      let checked = [];
      for (var i = 0; i < this.tsList.length; i++) {
        checked.push(this.tsList[i].sourceId);
      }
      this.checkedCombo = val ? checked : [];
     if (this.checkedCombo.length == 0) {
        // let {oldTotalMoney , newTotalMoney , discountMoney} = calculate.calculateTotalByList(this.tsList)
        // this.totalMoney -= oldTotalMoney;
        // this.total -= newTotalMoney;
        // this.disAmount = 0.0;
      } else {
        // let {oldTotalMoney , newTotalMoney , discountMoney} = calculate.calculateTotalByList(this.tsList);
        // this.total+=newTotalMoney;
        // this.totalMoney+=oldTotalMoney;
        // this.disAmount+=discountMoney;
      }
    },
    //特殊收费
    tsChange(value, id, money) {
      let checkedCount = value.length;
      this.checkComboAll = checkedCount === this.tsList.length;
      let bools = value.includes(id);
      // if(bools){
      //     this.total+=Number(money);
      //     this.totalMoney+=Number(money);
      //   }else{
      //     this.total-=money;
      //     this.totalMoney-=money;
      //   }
    },
    //预先提交提示
    onBeforeSubmit() {
      let checkadmin=[];
      let checkTsList=[];
      let returnNumber=0;
      this.itemList.map(it=>{
          if(this.checkedAdmin.includes(it.sourceId) && it.refundAmount==0 ){
             this.$message.warning(`请输入${it.sourceName}的退费金额`);
             returnNumber++;
          }
          if(this.checkedAdmin.includes(it.sourceId) && !it.packageWriteOff && it.refundAmount!=0){
            checkadmin.push(it);
          }
      })
      this.tsList.map(it=>{
          if(this.checkedCombo.includes(it.sourceId) && it.refundAmount!=0){
            checkTsList.push(it);
          }
      })
      this.checkItemList=checkadmin;
      this.tsItemList=checkTsList;
      if(returnNumber>0){
        return false;
      }
      if(checkadmin.length<1 && checkTsList.length<1){
        this.$message.warning("请选择需要退费的项目");
        return false;
      }
      this.showReturn=true;
    },
    goBack() {
      this.$router.go(-1);
    },
    doPrint() {
      this.showOrder = true;
      this.showLoading();
      setTimeout(()=> {
        this.iframeContent = this.$refs.iframe.contentWindow;
        this.iframeContent.postMessage(
          {
            cmd: "postJson",
            params: JSON.stringify({
              detail: this.detail,
              disAmount: Number(this.disAmount).toFixed(2) ,
              list: this.itemList,
              doctor:this.doctorName,
              dept:this.deptName,
              special: this.tsList, //特殊收费
              logo: this.adminUser.printLogo,
              orderCode: '',
              total: Number(this.totalMoney).toFixed(2),
              hospitalName: this.adminUser.hospitalName,
            }),
          },
          "*"
        );
      }, 500);
      setTimeout(()=> {
        this.showLoading(false);
      }, 2000);
    },
    handleCheckAllChange(val){
      let checked = [];
      const item=this.itemList;
      const tcList=this.tsList;
      for (var i = 0; i < item.length; i++) {
        checked.push(item[i].sourceId);
      }
      this.checkedAdmin = val ? checked : [];
      let ilist=[];
      let tcIlist=[];
      if (this.checkedAdmin.length > 0) {
        item.forEach(it=>{
          if(checked.includes(it.sourceId)){
            ilist.push(it);
          }
        })
      }
      if (this.checkedCombo.length > 0) {
        tcList.forEach(it=>{
          if(this.checkedCombo.includes(it.sourceId)){
            tcIlist.push(it);
          }
        })
      }
      // let {oldTotalMoney , newTotalMoney , discountMoney} = calculate.calculateTotalByList(ilist);
      // let tcObj= calculate.calculateTotalByList(tcIlist);
      // this.total=Number(newTotalMoney+tcObj.newTotalMoney);
      // this.totalMoney=Number(oldTotalMoney+tcObj.oldTotalMoney);
      // this.disAmount=Number(discountMoney+tcObj.discountMoney);
      // this.isCombo = false;
    },
    getDetail(obj){
      this.showDetail=true;
      this.sourceId=obj.sourceId;
    }
  },
  components:{
    dialogReturn:dialogReturn,
    dialogTcDetail:dialogTcDetail
  }
};
</script>
<style lang="scss" scoped>
@import "../_css/detail.scss";
.patient_img {
  border: 1px solid #ddd;
  border-radius: 5px;
  display: inline-block;
  width: 100px;
  height: 100px;
}
.durg_title {
  display: inline-block;
  width: 100%;
  font-size: 16px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
  margin-bottom: 10px;
}

.money_box {
  margin-top: 10px;
  display: inline-block;
  width: 100%;
  .other {
    height: 10px;
    display: inline-block;
  }
  .money {
    text-align: right;
    padding-right: 10px;
    display: inline-block;
  }
}
.printOrder {
  display: inline-block;
  width: 100%;
}
</style>

